package controller.upms;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import wt.entity.upms.*;
import wt.staticData.ShortData;
import wt.webPlugin.ZTree;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.upms.AccountPermissionServices;
import services.upms.PermissionRoleServices;
import services.upms.PermissionServices;
import util.key.IDFactory;
import validator.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller

@RequestMapping("upms/permission")
public class PermissionController extends BaseController {
    @Autowired
    PermissionServices permissionServices;

    @Autowired
    PermissionRoleServices permissionRoleServices;
    @Autowired
    AccountPermissionServices accountPermissionServices;

    @RequiresPermissions("upms:permission:default")
    @RequestMapping("index")
    public String index() {
        return "upms/permission/index";
    }


    @RequiresPermissions("upms:permission:default")
    @RequestMapping("editDlg")
    public String addUpdateDlg(@RequestParam(value = "id", required = false) String id, Map map) throws Exception {

        if (id != null) {
            Permission permission = null;
            permission = permissionServices.selectByPrimaryKey(id);

            if (permission == null) {
                map.put(StaticConstant.ERROR_MESSAGE, StaticConstant.NOT_FOUND_DATA);
                return StaticConstant.ERROR_DLG;
            }

            map.put(StaticConstant.EDIT_DATA, permission);
            map.put(StaticConstant.EDIT_URL, "upms/permission/update");
            map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_UPDATE);
        } else {
            map.put(StaticConstant.EDIT_URL, "upms/permission/insert");
            map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);
        }
        return "upms/permission/editDlg";
    }

    @RequiresPermissions("upms:permission:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult add(Permission permission) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(permission.getName(), new NotBlankFluentValidator("名称"))
                .on(permission.getLive(), new NotNullFluentValidator("状态"))
                .on(permission.getType(), new NotNullFluentValidator("类型"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }

        permission.setId(IDFactory.getSnowflakeId());
        permission.setCreateTime(new Date());
        if (permission.getOrders() == null) {
            permission.setOrders(new Date().getTime());
        }
        permission.setPermission(permission.getPermission() == null ? null : permission.getPermission().trim());
        permission.setRequestPermission(permission.getRequestPermission() == null ? null : permission.getRequestPermission().trim());


        permissionServices.insertSelective(permission);

        return commonResult.setSuccess();
    }

    @RequiresPermissions("upms:permission:default")
    @ResponseBody
    @RequestMapping("update")
    public CommonResult update(Permission permission) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(permission.getName(), new NotBlankFluentValidator("名称"))
                .on(permission.getLive(), new NotNullFluentValidator("状态"))
                .on(permission.getType(), new NotNullFluentValidator("类型"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }
        permission.setPermission(permission.getPermission() == null ? null : permission.getPermission().trim());
        permission.setRequestPermission(permission.getRequestPermission() == null ? null : permission.getRequestPermission().trim());
        permissionServices.updateByPrimaryKeySelective(permission);

        return commonResult.setSuccess();
    }

    @RequiresPermissions("upms:permission:default")
    @ResponseBody
    @RequestMapping("delete")
    public CommonResult delete(@RequestParam("id") String id) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();

        Integer counts;
        counts = permissionServices.deleteByPrimaryKey(id);

        if (counts == 0) {
            commonResult.addMessage(StaticConstant.NOT_FOUND_DATA);
            return commonResult.setError();
        }
        return commonResult.setSuccess();
    }


    /**
     * 权限主页展示 （包含停用）
     *
     * @return
     */
    @RequiresPermissions("upms:permission:default")
    @ResponseBody
    @RequestMapping("select")
    public List<Permission> select() throws Exception {
        List<Permission> permissionList = null;
        PermissionExample permissionExample = new PermissionExample();
        permissionExample.setOrderByClause("orders");
        permissionList = permissionServices.selectByExample(permissionExample);

        return permissionList;
    }


    /************************************************
     *
     * 公共方法
     *
     ***********************************************/


    /**
     * 获取编号为id节点的儿子节点（去除停用）
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("selectSon")
    public JSONArray selectSon(String id) throws Exception {

        PermissionExample permissionExample = new PermissionExample();
        permissionExample.setOrderByClause("orders");
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andLiveEqualTo(ShortData.s1);
        if (StringUtils.isEmpty(id)) {
            criteria.andPidIsNull();
        } else {
            criteria.andPidEqualTo(id);
        }
        List<Permission> permissionList = permissionServices.selectByExample(permissionExample);
        return ZTree.permission2ZTreeJSONArray(permissionList);

    }


    /**
     * 获取所有启用权限
     *
     * 用途：创建角色时获取权限树
     *
     * @return
     */

    @ResponseBody
    @RequestMapping("selectAllActivePermission")
    public JSONArray selectAllActivePermission() throws Exception {

        PermissionExample permissionExample = new PermissionExample();
        permissionExample.setOrderByClause("orders");
        permissionExample.createCriteria().andLiveEqualTo((short) 1);
        List<Permission> permissionList    = permissionServices.selectByExample(permissionExample);

        return ZTree.permission2ZTreeJSONArray(permissionList);
    }


    /**
     * 获取角色的具有的启用权限，剔除了停用权限
     * 用途：修改角色时获取角色权限 。创建、修改账户时获取角色权限
     *
     * @param roleId
     * @return
     */

    @ResponseBody
    @RequestMapping("selectAllActivePermissionByRoleId")
    public JSONArray selectAllActivePermissionByRoleId(@RequestParam(value = "roleId") String roleId) throws Exception {


        PermissionRoleExample permissionRoleExample = new PermissionRoleExample();
        permissionRoleExample.createCriteria().andRoleIdEqualTo(roleId);
        List<PermissionRole> permissionRoleList = permissionRoleServices.selectByExample(permissionRoleExample);

        JSONArray ZTreeList = selectAllActivePermission();
        if (ZTreeList != null) {
            for (int i = 0; i < ZTreeList.size(); i++) {
                JSONObject ZTreeNode = ZTreeList.getJSONObject(i);
                for (PermissionRole permissionRole : permissionRoleList) {
                    if (ZTreeNode.getString(ZTree.ID).equals(permissionRole.getPermissionId())) {
                        ZTreeNode.put(ZTree.CHECKED, true);
                    }
                }
            }
        }
        return ZTreeList;

    }


    /**
     * 获取角色的权限所有的权限（包含停用）
     * <p>
     * 用途：角色权限的展示
     *
     * @param roleId
     * @return
     */

    @ResponseBody
    @RequestMapping("selectAllPermissionByRoleId")
    public JSONArray selectAllPermissionByRoleId(@RequestParam(value = "roleId") String roleId) throws Exception {

        List<Permission> permissionList = permissionServices.selectByRoleId(roleId);

        return ZTree.permission2ZTreeJSONArray(permissionList);
    }


    /**
     * 获取用户的权限
     * 用途：用户权限的修改时的展示
     *
     * @param accountId
     * @return
     */

    @ResponseBody
    @RequestMapping("selectByAccountIdWithAll")
    public JSONArray selectByAccountIdWithAll(String accountId) throws Exception {


        AccountPermissionExample accountPermissionExample = new AccountPermissionExample();
        accountPermissionExample.createCriteria().andAccountIdEqualTo(accountId);
        List<AccountPermission> accountPermissionList = accountPermissionServices.selectByExample(accountPermissionExample);

        JSONArray ZTreeList = selectAllActivePermission();

        if (ZTreeList != null) {
            for (int i = 0; i < ZTreeList.size(); i++) {
                JSONObject ZTreeNode = ZTreeList.getJSONObject(i);
                for (AccountPermission accountPermission : accountPermissionList) {
                    if (ZTreeNode.getString(ZTree.ID).equals(accountPermission.getPermissionId())) {
                        ZTreeNode.put(ZTree.CHECKED, true);
                    }
                }
            }

        }
        return ZTreeList;
    }


}